package org.example.codeservce.config;


import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.dashscope.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.example.codeservce.entity.MessageJson;
import org.example.codeservce.entity.Order;
import org.example.codeservce.service.WebSocketService;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.net.URI;

@Component
@Slf4j
public class MyWebSocketHandler extends TextWebSocketHandler
{

    private WebSocketService webSocketService;

    public MyWebSocketHandler(WebSocketService webSocketService)
    {
        this.webSocketService = webSocketService;
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception
    {
        log.info("连接上：" + JsonUtils.toJson(session.getId()));
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception
    {
        try
        {
            // 连接建立时触发
            webSocketService.execute(session, JSONUtil.toBean(message.getPayload(), Order.class));
            log.info("WebSocket connection established: " + session.getId());
        } catch (Exception e)
        {
            session.sendMessage(new TextMessage("查询订单失败:"+e.getMessage()));
        }
    }
}